package view;

import facade.CompetenceFacade;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import model.Competence;

/**
 *
 * @author ZimmE
 */
@FacesConverter(forClass = Competence.class)
public class CompetenceConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext ctx, UIComponent comp, String value) {
        CompetenceFacade competenceFacade = null;
        try {
            BeanManager bm = (BeanManager) new InitialContext().lookup("java:comp/BeanManager");
            Bean<CompetenceFacade> bean = (Bean<CompetenceFacade>) bm.getBeans(CompetenceFacade.class).iterator().next();
            CreationalContext<CompetenceFacade> cctx = bm.createCreationalContext(bean);
            competenceFacade = (CompetenceFacade) bm.getReference(bean, CompetenceFacade.class, cctx);
        } catch (NamingException ex) {
            Logger.getLogger(CompetenceConverter.class.getName()).log(Level.SEVERE, null, ex);
        }
        return competenceFacade.find(Integer.parseInt(value));

    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        return String.valueOf(((Competence) value).getCompetenceId());
    }
}
